void main() {
  print('Hello, Dart!');
  print(addStrings("123", "4567")); // 输出 "4690"

  // q：有哪些变量定义方式
  // A: var, final, const, dynamic
  var name = "Alice"; // 类型推断为 String
  final age = 30; // 类型推断为 int，值不可变
  const pi = 3.14; // 类型推断为 double，编译时常量
  dynamic something = "Hello"; // 可以改变类型
  something = 42; // 现在是 int 类型

  // q：Dart 有哪些基本数据类型
  // A: int, double, String, bool, List, Map, Set, Rune, Null
  int count = 10;
  double price = 19.99;
  String message = "Dart is fun!";
  bool isActive = true;
  List<int> numbers = [1, 2, 3];
  Map<String, int> scores = {'Alice': 90, 'Bob': 85};
  Set<String> uniqueNames = {'Alice', 'Bob'};
  var heart = Runes('\u2665');
  Null nothing = null;
  print('$name, $age, $pi, $something');
  print('$count, $price, $message, $isActive');
  print('Heart symbol: ${String.fromCharCodes(heart)}');
  print('$numbers, $scores, $uniqueNames, $nothing');

  // q: Dart 有哪些流程控制语句
  // A: if, else, for, while, do-while, switch, case, break, continue
  if (isActive) {
    print("$name is active");
  } else {
    print("$name is not active");
  }

  for (var number in numbers) {
    print("Number: $number");
  }

  int i = 0;
  while (i < 3) {
    print("While loop i: $i");
    i++;
  }

  for (int j = 0; j < 3; j++) {
    print("For loop j: $j");
  }
  switch (age) {
    case 20:
      print("Age is 20");
      break;
    case 30:
      print("Age is 30");
      break;
    default:
      print("Age is something else");
  }

  do {
    print("This is a do-while loop that will not execute.");
  } while (false);

  // q: Dart 有哪些函数定义方式
  // A: 普通函数, 匿名函数, 箭头函数, 递归函数
  int add(int a, int b) {
    return a + b;
  }

  // 匿名函数
  var multiply = (int a, int b) {
    return a * b;
  };

  // 箭头函数
  int subtract(int a, int b) => a - b;

  // 递归函数
  int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
  }

  print("Factorial of 5: ${factorial(5)}");
}
// 告诉我编译成 exe 的脚本
// dart compile exe  -o demo.exe
/**
 * 给你两个数字字符串，编写一个方法计算两数之和，并用字符串输出结果。
 */

String addStrings(String num1, String num2) {
  StringBuffer result = StringBuffer();
  int carry = 0;
  int i = num1.length - 1;
  int j = num2.length - 1;

  while (i >= 0 || j >= 0 || carry > 0) {
    int digit1 = i >= 0 ? num1.codeUnitAt(i) - '0'.codeUnitAt(0) : 0;
    int digit2 = j >= 0 ? num2.codeUnitAt(j) - '0'.codeUnitAt(0) : 0;

    int sum = digit1 + digit2 + carry;
    carry = sum ~/ 10; // 计算进位
    result.writeCharCode((sum % 10) + '0'.codeUnitAt(0));

    i--;
    j--;
  }

  return result.toString().split('').reversed.join('');
}
